package com.zd.web.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zd.entity.Chapter;
import com.zd.entity.NovelWriterType;
import com.zd.entity.User;
import com.zd.service.NovelService;
import com.zd.service.impl.NovelServiceImpl;

/**
 * Servlet implementation class ShuServlet
 */

@WebServlet("/ShuServlet")
public class ShuServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	NovelService novelService=new NovelServiceImpl();
   
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		String novelId=request.getParameter("novelId");
		request.setAttribute("novelId", novelId);
		User user=(User)request.getSession().getAttribute("user");
		if(user==null) {
  			response.sendRedirect("login.jsp");
  			return;
  		}
		//查一遍所有的小说type类型
		List<String> typeList=novelService.novelType();
		request.setAttribute("typeList", typeList);
		
		//查该小说
		List<NovelWriterType> novelById=novelService.selectnovelById(novelId);
		request.setAttribute("novelById", novelById);
		String introduction=novelById.get(0).getNovelIntroduction();
		introduction=introduction.replace("。", "。<br>");
//		System.out.println(introduction);
		request.setAttribute("introduction", introduction);
		
//		List<Chapter> shuChapter=novelService.selectshuChapter(novelId);
//		request.setAttribute("shuChapter", shuChapter);
		//查第几章数
		int chapterNum=novelService.selectChapterNum(novelId);
		request.setAttribute("chapterNum",chapterNum);
		//查最新章节
		Chapter nowChapter=novelService.selectNowChapter(novelId);
		request.setAttribute("nowChapter",nowChapter);
//		System.out.println(nowChapter);
		//查询章节id加名字
		List<Chapter> shuChapter=novelService.selectshuChapter(novelId);
  		request.setAttribute("shuChapter", shuChapter);
		//每张字数
  		int[] nums=new int[shuChapter.size()];
  		for(int i=0;i<shuChapter.size();i++) {
  			int num =shuChapter.get(i).getChapterContent().length();
  			nums[i]=num;
  		}
  		System.out.println(nums);
  		request.setAttribute("nums", nums);
  		//添加点击量
  		int numw=novelService.addHits(novelId);
  		//点击该书添加最近浏览记录
  		//查当前用户id
  		
  		
  		
  		int userId=user.getUserId();
  		//把userId和小说Id加入记录表
  		int c=novelService.addRead(userId,novelId);
		request.getRequestDispatcher("shu.jsp").forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
	}

}
